<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="view-table">
      <template #high_form="{ form }">
        <XForm ref="form" :fieldList="highFieldList" :options="formOption" labelPosition="top" :formData="form" :originOption="originOption" class="grid grid-cols-3" v-if="formShow" />
      </template>

      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="formShow">
          <template #monthrange>
            <el-date-picker v-model="form.value1" type="monthrange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" valueFormat="YYYY-MM-DD HH:mm:ss" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <!-- <VButton auth="/pmc/plan/stockUpFba/export" @click="onExport"> <svg-icon icon-class="import" /> 导出 </VButton> -->
        <VButton auth="/pmc/plan/stockUpFba/renewal" type="primary" @click="renewal"> 手动更新 </VButton>

        <!-- <el-button type="primary" @click="renewal">手动更新</el-button> -->

        <el-dropdown trigger="click" @command="batchOptionsEvent">
          <el-button type="primary">
            批量操作
            <div class="dk-iconfont icon-ArrowDown"></div>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu v-matomo>
              <template v-for="item in batchOptions" :key="item.label">
                <el-dropdown-item :command="item.value">{{ item.label }}</el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- <el-button type="primary" @click="batchUpdateConfirm">批量确认</el-button>
        <el-button type="primary" @click="addStockUp">创建备货计划</el-button>
        <el-button type="primary" @click="addMaterialPlan">创建备料计划</el-button> -->

        <VButton auth="/pmc/plan/stockUpFba/batchUpdateConfirm" type="primary" @click="batchUpdateConfirm"> 批量确认 </VButton>
        <VButton auth="/pmc/plan/stockUpFba/addStockUp" type="primary" @click="addStockUp"> 创建备货计划 </VButton>
        <VButton auth="/pmc/plan/stockUpFba/addMaterialPlan" type="primary" @click="addMaterialPlan"> 创建备料计划 </VButton>

        <el-dropdown trigger="click" @command="setFormData">
          <el-button type="danger">
            断货SKU筛选
            <div class="dk-iconfont icon-ArrowDown"></div>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu v-matomo>
              <el-dropdown-item command="1">库存可售断货</el-dropdown-item>
              <el-dropdown-item command="2">FBA可售断货</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <!-- <el-button type="primary" @click="onFullAnalysis">全量更新</el-button>
        <el-button class="ml-auto" @click="onExport">
          <span class="flex items-center"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </span>
        </el-button> -->

        <VButton auth="/pmc/plan/stockUpFba/fullAnalysis" type="primary" @click="onFullAnalysis"> 全量更新 </VButton>

        <div class="ml-auto">
          历史分析数据:
          <el-date-picker v-model="archived_at" style="width: 150px" type="date" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" />
        </div>
        <VButton auth="/pmc/plan/stockUpFba/export" @click="onExport"> <svg-icon icon-class="import" /> 导出 </VButton>
      </template>
    </VTable>
    <!-- ASIN销量趋势 -->
    <AsinSalesTrend ref="AsinSalesTrendRef" />
    <!-- 日志 -->
    <XLog ref="logRef" :api="stockingAnalysisLog" />

    <!-- 库存信息 -->
    <InventoryDtl ref="InventoryDtlRef" />
    <!-- 备料库存明细 -->
    <StockMaterial ref="StockMaterialRef" />
    <!-- 系统预估销量设置 -->
    <EstimatedSales ref="EstimatedSalesRef" />
    <!-- 弹窗 表单编辑 -->
    <ConfirmInput v-model="batchVisible" v-bind="currentConfirm" @submit="handleConfirmSubmit">
      <!-- 基础LT天数设置 -->
      <template #ltDay="{ form }">
        <div>
          <div class="basic_lead">
            <div class="text-[#f650a0] text-[18px]">
              {{ form?.basic_lead_time }}
            </div>
            <div class="text-[#999]">基础LT天数</div>
            <div class="text-[#999] text-[12px] mb-[8px]">基础LT天数 =采购处理天数 + 采购天数 + 本地仓处理天数 + 运输天数 + 海外中转仓处理天数 + 平台上架天数 + 安全天数；</div>
          </div>
          <div class="mt-[4px]">
            是否开启编辑 <el-switch v-model="form.is_manually_edit" :active-value="1" :inactive-value="0" @change="onIsManually" />
            <span class="ml-[12px]">提示：关闭后不可手动修改参数，系统会自动 同步基础设置>备货参数中的天数</span>
          </div>
        </div>
      </template>
      <!-- 批量设置备货参数 单位 -->
      <template #AppendDay>天</template>
    </ConfirmInput>
    <!-- 弹窗 表格数据展示 -->
    <DialogTableInfo v-model="dialogTableInfoVisible" v-bind="tableInfoConfirm" @close="closeTableInfo" />

    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>

    <el-dialog v-model="dialogVisible" title="提示" width="500" :show-close="false">
      <div class="text-center my-[40px]">
        <div class="mb-[16px]">
          sku：{{ stockingQuantityParams.sku }}，Asin：{{ stockingQuantityParams.asin }}
          <div>修改后的数量：{{ stockingQuantityParams.stocking_quantity }} 不满足整箱的倍数，是否继续保存；</div>
        </div>

        <el-button type="primary" @click="saveUpdateMaterialQuantity('mpq_min_quantity')">按整箱数</el-button>
        <el-button type="primary" @click="saveUpdateMaterialQuantity('quantity')">按填写值</el-button>
        <el-button @click="saveUpdateMaterialQuantity(false)">取消</el-button>
      </div>
    </el-dialog>
  </VPage>
</template>

<script setup lang="jsx">
import {
  stockingAnalysisList,
  batchUpdateLtDays,
  batchUpdateStockingStatus,
  updateInventory,
  stockingAnalysisLog,
  operateDailyAverageSales,
  purchaseDemandSkuList,
  purchaseDeliverPlan,
  stockingPlanCreate,
  purchaseMaterialPlanCreate,
  stockingAnalysisAnalysis,
  purchaseProcessHistory,
  updateStockingQuantity,
  updateMaterialQuantity,
  stockingCreatePlan,
  createMaterialPlan,
} from "@/api/plan"
import { batchUpdateConfirmStatus, updatePlanAverageDailySales, fullAnalysis, batchSettingManualEdit, historyList } from "./api.js"

import action from "@/utils/action.js"

import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"

const archived_at = ref("")

// ASIN销量趋势
import AsinSalesTrend from "@/views/plan/components/AsinSalesTrend/index.vue"
const AsinSalesTrendRef = ref()

// 日志
import XLog from "@/components/XLog"
const logRef = ref()

// 库存信息
import InventoryDtl from "./components/inventoryDtl.vue"
const InventoryDtlRef = ref()
// 备料库存明细
import StockMaterial from "./components/stockMaterial.vue"
const StockMaterialRef = ref()
// 系统预估销量设置
import EstimatedSales from "./components/estimatedSales.vue"
const EstimatedSalesRef = ref()

const router = useRouter()

// 全量更新
const onFullAnalysis = () => {
  ElMessageBox.confirm("确认全量执行备货分析?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      fullAnalysis().then((res) => {
        ElMessage({ type: "success", message: "操作完成" })
        query()
      })
    })
    .catch(() => {
      ElMessage({ type: "info", message: "已取消" })
    })
}
// 基础LT天数 是否开启编辑
const onIsManually = (e) => {
  let fieldOptions = [...currentConfirm.value.fieldOptions]
  currentConfirm.value.fieldOptions = []
  fieldOptions.forEach((item) => {
    item.disabled = e == 0
    if (item.field == "procurement_days") {
      item.disabled = true
    }
  })
  currentConfirm.value.fieldOptions = fieldOptions
}

// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const onExport = () => {
  let rows = tableRef?.value.$table.getCheckboxRecords()
  let condition = {}
  if (rows?.length) {
    condition.id = rows.map((v) => v.id)
  } else {
    condition = initForm(tableRef?.value?.getQueryForm())
  }
  DerivedCenterRef.value.open({ tag_name: "STOCKING_ANALYSIS_LIST", condition })
}

// 断货SKU筛选
const setFormData = (e) => {
  tableRef.value.resetForm()
  // 库存可售断货
  if (e == 1) {
    tableRef.value.setForm({ out_stock: "inventory" })
  }
  // FBA可售断货
  if (e == 2) {
    tableRef.value.setForm({ out_stock: "fba" })
  }
  query()
}
const handleFunction = ref({
  // 变更
  onUpdate: (row) => {
    sessionStorage.setItem("PURCHASE_HANDLE", JSON.stringify({ pds_id: row.pds_id, demand_no: row.demand_no, sku: row.sku, sku_no: row.sku_no }))
    action.setGlobalState({
      changeMicoTabsPath: {
        path: "/purchase/demand/sku",
        type: "push",
      },
    })
  },

  deliverPlan: (row) => {
    purchaseDeliverPlan({ pds_ids: [row.pds_id], is_skip: 1 }).then((res) => {
      ElMessageBox.confirm(`${res?.data?.fail_message}`, "提示", {
        showConfirmButton: false,
        cancelButtonText: "关闭",
        type: "warning",
      })
    })
  },
})

const batchUpdateConfirm = () => {
  //batchUpdateConfirmStatus
  let list = getSelectRow()
  if (!list.length) {
    return ElMessage({ showClose: true, message: "请选择数据进行操作", type: "warning" })
  }
  // console.log(list)
  ElMessageBox.confirm(`确认修改${list.length}条数据`, "提示信息", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      batchUpdateConfirmStatus({
        ids: list.map((v) => v.id),
        confirm_status: 1,
      }).then((res) => {
        ElMessage.success(res.message)
        query()
      })
    })
    .catch(() => {
      ElMessage({ type: "info", message: "取消" })
    })
}

import XForm from "@/components/XForm/index.vue"
const formShow = ref(false)
//获取下拉数据
onMounted(() => {
  getOption()
  setTimeout(() => {
    nextTick(() => {
      formShow.value = true
      // 操作
      handleFunctions.value = { ...handleFunctions.value, ...handleFunction.value }
    })
  }, 200)
})

// 枚举 数据
const originOption = ref({})
// 表单组件配置
const formOption = ref({})

import { fieldList, highFieldList, batchOConfig, dialogTabelInfoConfig, handleFunctions } from "./config.jsx"

// 弹窗 表格数据展示
import DialogTableInfo from "@/components/DialogTableInfo/index.vue"
const dialogTableInfoVisible = ref(false)
const tableInfoConfirm = ref({})

const openTableInfo = async (type, row = {}) => {
  let confirm = {}
  switch (type) {
    case "historyPurchase":
      // 历史采购订单价格
      confirm = dialogTabelInfoConfig.historyPurchase
      let res = await purchaseProcessHistory({ sku: row?.sku })
      confirm.info = { sku: res.data.sku, sku_name: res.data.sku_name }
      confirm.tableOptions.data = res.data?.list
      break
    case "forecastSales": // 运营预测日均销量
      await operateDailyAverageSales({ base_asin_id: row.id }).then((res) => {
        confirm = dialogTabelInfoConfig.forecastSales
        confirm.tableOptions.columns = confirm.tableOptions.columns.filter((v) => v.isType != "month")
        let columns = res.data.sales_forecast.map((v) => ({ ...confirm.dayColumns, title: v.month }))
        confirm.tableOptions.columns.push(...columns)
        res.data.sales_forecast.forEach((item) => {
          res.data[item.month] = item
        })
        confirm.tableOptions.data = [res.data]
      })
      break
    case "purchaseDemandSku": // 待下PO明细
      await purchaseDemandSkuList({
        sku: row.sku,
        demand_type: [2],
        sku_purchase_status: [1, 2, 3, 4, 5, 6],
        demand_status: [1, 2, 3, 4, 5, 8, 9, 11, 12],
        country: row.site_code ? [row.site_code] : [],
        asin: row.asin,
      }).then((res) => {
        confirm = dialogTabelInfoConfig.purchaseDemandSku
        confirm.info = { sku: row.sku, asin: row.asin }
        confirm.tableOptions.data = res.data
      })
      break
    case "purchaseDemandSkuNo": // 未完结PR数
      await purchaseDemandSkuList({
        sku: row.sku,
        demand_type: [2],
        // sku_purchase_status: [6, 7],
        plan_order_status: [1, 2],
        demand_status: [9, 11],
        country: row.site_code ? [row.site_code] : [],
        is_complete: [1],
        asin: row.asin,
      }).then((res) => {
        confirm = dialogTabelInfoConfig.purchaseDemandSkuNo
        confirm.info = { sku: row.sku, asin: row.asin }
        confirm.tableOptions.data = res.data
      })
      break
    default:
      break
  }
  tableInfoConfirm.value = confirm
  dialogTableInfoVisible.value = true
}
const closeTableInfo = () => {
  tableInfoConfirm.value = {}
}

const tableRef = ref()

// 弹窗 表单编辑
import ConfirmInput from "@/components/ConfirmInput/index.vue"
const batchVisible = ref(false)
const currentConfirm = ref({})

const batchOptions = [
  { label: "批量设置备货参数", value: "lt_days", permission: [] },
  { label: "批量设置备货状态", value: "stocking_status", permission: [] },
  // { label: "批量设置系统预估销量", value: "wwwsss", permission: [] },
  { label: "批量关闭手动调整LT天数", value: "isManuallyEdit", permission: [] },
]
const addStockUp = () => {
  let list = getSelectRow()
  if (list.find((v) => v.plan_stocking_analysis.stocking_quantity == 0)) {
    return ElMessage({ showClose: true, message: "需求数为0的不能生成备货计划", type: "warning" })
  }
  let params = {
    base_asin_ids: list.map((v) => v.id),
  }
  stockingCreatePlan(params).then((res) => {
    ElMessage.success(res.message)
  })
}
// 创建备料计划
const addMaterialPlan = () => {
  // createMaterialPlan
  let list = getSelectRow()
  if (!list.length) return

  ElMessageBox.confirm(`创建${list.length}条备料计划`, "提示信息", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      createMaterialPlan({
        base_asin_ids: list.map((v) => v.id),
      }).then((res) => {
        ElMessage.success(res.message)
        query()
      })
    })
    .catch(() => {
      ElMessage({ type: "info", message: "取消" })
    })
}

const batchOptionsEvent = (e) => {
  let list = getSelectRow()
  if (!list.length) return ElMessage({ message: "请选择数据进行操作", type: "warning" })
  if (e == "isManuallyEdit") {
    ElMessageBox.confirm(`关闭${list.length}条数据手动调整LT天数`, "提示信息", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        batchSettingManualEdit({
          base_asin_id: list.map((v) => v.id),
          is_manually_edit: "0",
        }).then((res) => {
          ElMessage.success(res.message)
          query()
        })
      })
      .catch(() => {
        ElMessage({ type: "info", message: "取消" })
      })

    updateStockingQuantity({
      base_asin_id: [row.id],
      stocking_quantity: row?.plan_stocking_analysis.stocking_quantity,
    }).then((res) => {
      ElMessage.success(res.message)
      query()
    })
  }
  if (["lt_days", "stocking_status"].includes(e)) {
    openConfirmInput(e, { ids: list.map((v) => v.id) })
  } else {
    EstimatedSalesRef.value.open(list.map((v) => v.id))
  }
}
const openInput = (e, row) => {
  openConfirmInput(e, row)
}

const openConfirmInput = (type, params = {}) => {
  let confirm = {}
  switch (type) {
    case "base_lt_days": // 编辑 基础LT天数设置
      confirm = batchOConfig.base_lt_days
      confirm.form = { ids: [params.id] }
      let keys = confirm.fieldOptions.map((v) => v.field)
      keys.forEach((key) => {
        confirm.form[key] = params.plan_lt_days[key]
      })
      confirm.form.is_manually_edit = params.plan_lt_days.is_manually_edit
      console.log(confirm.form)

      confirm.originOption = originOption.value

      confirm.fieldOptions.forEach((item) => {
        item.disabled = params.plan_lt_days.is_manually_edit == 0
        if (item.field == "procurement_days") {
          item.disabled = true
        }
      })

      break
    case "lt_days": // 批量设置备货参数
      confirm = batchOConfig.lt_days
      confirm.form = { ids: params.ids }
      break
    case "stocking_status": // 批量设置备货状态
      confirm = batchOConfig.stocking_status
      confirm.form = { ids: params.ids }
      confirm.length = params.ids.length
      confirm.originOption = originOption.value
      break
    case "overseas": // 修改库存信息
      confirm = batchOConfig.overseas
      confirm.form = {
        base_asin_id: params.id,
        overseas_warehouse_available: params.plan_asin_inventory.overseas_warehouse_available,
        fba_available: params.plan_asin_inventory.fba_available,
        overseas_warehouse_in_transit: params.plan_asin_inventory.overseas_warehouse_in_transit,
        fba_in_transit: params.plan_asin_inventory.fba_in_transit,
      }
      confirm.originOption = originOption.value
      break
  }
  confirm.type = type
  currentConfirm.value = confirm

  batchVisible.value = true
}

const dialogVisible = ref(false)
const stockingQuantityParams = ref({})
// 修改 需求数量
// stocking_quantity material_quantity
const updateQuantity = (row, type = "") => {
  if (row.plan_stocking_analysis[type] % row.plan_asin_purchases.mpq_min_quantity != 0) {
    dialogVisible.value = true
    stockingQuantityParams.value = {
      base_asin_id: [row.id],
      stocking_quantity: row?.plan_stocking_analysis.stocking_quantity,
      material_quantity: row?.plan_stocking_analysis.material_quantity,
      mpq_min_quantity: row?.plan_asin_purchases.mpq_min_quantity,
      sku: row.sku,
      asin: row.asin,
      type,
    }
  } else {
    if (type == "stocking_quantity") {
      // 修改 需求数量
      updateStockingQuantity({
        base_asin_id: [row.id],
        stocking_quantity: row?.plan_stocking_analysis.stocking_quantity,
      }).then((res) => {
        ElMessage.success(res.message)
        query()
      })
    } else {
      // 修改备料需求数量
      updateMaterialQuantity({
        base_asin_id: [row.id],
        material_quantity: row?.plan_stocking_analysis.material_quantity,
      }).then((res) => {
        ElMessage.success(res.message)
        query()
      })
    }
  }
}

const saveUpdateMaterialQuantity = (type) => {
  if (!type) {
    query()
    dialogVisible.value = false
    stockingQuantityParams.value = {}
    return
  }
  if (stockingQuantityParams.value.type == "stocking_quantity") {
    // 修改 需求数量
    if (type == "mpq_min_quantity") {
      let stocking_quantity = Math.ceil(stockingQuantityParams.value.stocking_quantity / stockingQuantityParams.value.mpq_min_quantity) * stockingQuantityParams.value.mpq_min_quantity
      stockingQuantityParams.value.stocking_quantity = stocking_quantity || 0
    }
    updateStockingQuantity({
      base_asin_id: stockingQuantityParams.value.base_asin_id,
      stocking_quantity: stockingQuantityParams.value.stocking_quantity,
    }).then((res) => {
      ElMessage.success(res.message)
      query()
      dialogVisible.value = false
      stockingQuantityParams.value = {}
    })
  } else {
    // 修改备料需求数量
    if (type == "mpq_min_quantity") {
      let material_quantity = Math.ceil(stockingQuantityParams.value.material_quantity / stockingQuantityParams.value.mpq_min_quantity) * stockingQuantityParams.value.mpq_min_quantity
      stockingQuantityParams.value.material_quantity = material_quantity
    }
    updateMaterialQuantity({
      base_asin_id: stockingQuantityParams.value.base_asin_id,
      material_quantity: stockingQuantityParams.value.material_quantity,
    }).then((res) => {
      ElMessage.success(res.message)
      query()
      dialogVisible.value = false
      stockingQuantityParams.value = {}
    })
  }
}

// // 修改备料需求数量
// const onUpdateMaterialQuantity = (row) => {
//   updateMaterialQuantity({
//     base_asin_id: [row.id],
//     material_quantity: row?.plan_stocking_analysis.material_quantity,
//   }).then((res) => {
//     ElMessage.success(res.message)
//     query()
//   })
// }

const handleConfirmSubmit = (param) => {
  // console.log(param)
  let params = {}
  let requests = null
  switch (currentConfirm.value.type) {
    case "base_lt_days": // 编辑 基础LT天数设置
      requests = batchUpdateLtDays
      params = {
        ids: param.ids,
        lt_days: JSON.parse(JSON.stringify(param)),
      }
      delete params.lt_days.ids
      break
    case "lt_days": // 批量设置备货参数
      requests = batchUpdateLtDays
      params = {
        ids: param.ids,
        lt_days: JSON.parse(JSON.stringify(param)),
      }
      delete params.lt_days.ids
      break
    case "stocking_status": // 批量设置备货状态
      requests = batchUpdateStockingStatus
      params = { ...param }
      break
    case "overseas": // 修改库存信息
      requests = updateInventory
      params = { ...param }
      break
    default:
      break
  }
  requests(params).then((res) => {
    ElMessage.success(res.message)
    batchVisible.value = false
    nextTick(() => {
      currentConfirm.value = {}
    })
    query()
  })
}

// 执行备货分析 手动更新
const renewal = async () => {
  let list = getSelectRow()
  if (!list.length) return
  stockingAnalysisAnalysis({ base_asin_ids: list.map((v) => v.id) }).then((res) => {
    ElMessage.success(res.message)
    query()
  })
}
// 更新计划预测日均
const dailySalesChange = (row) => {
  let params = {
    base_asin_id: row.id,
    plan_average_daily_sales: Number(row.plan_stocking_analysis.plan_average_daily_sales),
  }
  updatePlanAverageDailySales(params).then((res) => {
    ElMessage.success(res.message)
    query()
  })
}
// 获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    return false
  }
  return getCheckboxRecords
}

// 查询
const query = () => {
  tableRef?.value.query()
}

const sorting = ref({
  sorting_key: "",
  sorting_method: "",
})
const onSort = (key, method) => {
  let obj = {
    ...tableRef?.value.getForm(),
    sorting_key: key,
    sorting_method: method,
  }
  tableRef?.value.setForm(obj)
  query()
}

const activityColor = {
  新品: "text-green",
  重点: "text-red",
  // text-blue
}
// 已驳回: "base-danger-tag",
// 已审核: "base-info-tag",

// const salesTagColor = {
//   呆滞: "border-[#FAAD14] bg-[#FAAD14]",
//   清库: "border-[#E50113] bg-[#E50113]",
//   停售: "border-[#999] bg-[#999]",
// }
const salesTagColor = {
  呆滞: "base-tag-warning",
  清库: "base-tag-danger",
  停售: "base-tag-purple",
  default: "base-tag-primary",
}
const supplyStatusColor = {
  正常: "base-tag-success",
  default: "border-[var(--base-info-bg)] bg-[var(--base-info-bg) text-[#333]] ",
  // default: "base-info-plain-tag",
  default: "base-tag-info-plain",
}
const rowStyle = () => {}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    save: "/pmc/plan/stockUpFba", // 必填，唯一
    data: {
      skuRange: { type: "sku", value: "" },
      sorting_key: "",
      sorting_method: "",
    },
  },
  showOverflow: false,
  rowConfig: { height: "132" },
  columns: [
    { type: "checkbox", fixed: "left", width: 40 },
    {
      title: "图片",
      width: 120,
      fixed: "left",
      slots: {
        // <div>{row?.plan_stocking_analysis?.is_prepared_material_text}</div>
        default: ({ row }) => (
          <div>
            <el-image style="width:80px;height:80px" src={row.sku_attr_img} />
          </div>
        ),
      },
    },

    {
      title: "产品信息",
      width: 200,
      fixed: "left",
      slots: {
        // SKU销售状态 SKU货源状态
        //  <div class={`status-tag border-[1px] ${row.supply_status_text == "正常" ? "bg-[var(--base-success-bg)]" : "bg-[var(--base-info-bg)] "}`}>{row.supply_status_text}</div>

        default: ({ row }) => (
          <div>
            <div class="flex items-center w-[100%]">
              <div class="flex mr-[4px]">
                <div class={`status-tag  mr-[2px] ${salesTagColor[row.sales_status_text] || salesTagColor.default}`}>{row.sales_status_text}</div>
                <div class={`status-tag  ${supplyStatusColor[row.supply_status_text] || supplyStatusColor.default}`}>{row.supply_status_text}</div>
              </div>

              <div class="text-blue flex-1 w-[80px]">
                <VText title="SKU" value={row.sku} line={1} />
              </div>
            </div>

            <VText title="自定义" value={row.custom_sku} line={1} />
            <VText title="ASIN" value={row.asin} line={1} />
            <VText title="店铺" value={row.store_name} line={1} />

            <div class="flex items-center">
              <VText title="国家" value={row.site_code} line={1} />
              <VText title="活跃度" value={row.activity_status_text} line={1} class={activityColor[row.activity_status_text] || ""} />
            </div>
          </div>
        ),
      },
    },
    {
      title: "产品名称",
      width: 180,
      fixed: "left",
      slots: {
        default: ({ row }) => (
          <div>
            <VText value={row.sku_title} line={2} />
          </div>
        ),
      },
    },

    {
      title: "需求数量",
      width: 160,
      fixed: "left",
      slots: {
        default: ({ row }) => (
          <div>
            <el-input v-model={row.plan_stocking_analysis.stocking_quantity} placeholder="需求数量" style="width: 80px" onblur={() => updateQuantity(row, "stocking_quantity")} class="my-[4px]" />
            <div class="flex items-center mt-[2px]">
              <div class="">{row.plan_stocking_analysis.confirm_status_text || "-"}</div>
              <el-divider direction="vertical" />
              <div class="w-[70px]">
                <VText value={row.plan_stocking_analysis.stocking_remark || "-"} line={1} />
              </div>
            </div>
            <div>{row.plan_stocking_analysis.stocking_status_text || "-"}</div>

            {row.is_requires_stocking == 1 ? (
              <div class="flex items-center mt-[2px]">
                <div class="">备料:</div>
                <el-divider direction="vertical" />
                <div class="w-[70px]">
                  <el-input v-model={row.plan_stocking_analysis.material_quantity} placeholder="数量" style="width: 80px" onblur={() => updateQuantity(row, "material_quantity")} class="my-[4px]" />
                </div>
              </div>
            ) : (
              ""
            )}
          </div>
        ),
      },
    },

    {
      title: "待下PO数",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <p class="cursor-pointer text-[#3487ff]" onClick={() => openTableInfo("purchaseDemandSkuNo", row)}>
              未完结PR数 {row.plan_stocking_analysis.unfinished_pr_count}
            </p>
            <p class="cursor-pointer text-[#3487ff]" onClick={() => openTableInfo("purchaseDemandSku", row)}>
              待下PO数 {row.plan_stocking_analysis.pending_order_po_count}
            </p>
            <p class="cursor-pointer text-[#3487ff]" onClick={() => openTableInfo("historyPurchase", row)}>
              历史采购价格
            </p>
          </div>
        ),
      },
    },
    {
      title: "基础LT天数",
      width: 320,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <svg-icon icon-class="edit_icon" class="cursor-pointer text-[#3487ff] text-[16px] mr-[4px]" onClick={() => openInput("base_lt_days", row)} />
              {row.is_requires_stocking == 1 ? (
                <div class="mr-[12px]">
                  备料前: {row.plan_lt_days.basic_lead_time} 备料后: {row.plan_lt_days.prepare_basic_lead_time}
                </div>
              ) : (
                <div>{row.plan_lt_days.basic_lead_time}天，</div>
              )}
              <span class="text-[red]">总可售{row.plan_lt_days.total_available_days}天</span>
            </div>
            {row.is_requires_stocking == 1 ? (
              <VText title="采购天数" value={String(row.plan_lt_days.prepare_purchase_day) ? row.plan_lt_days.prepare_purchase_day + "天" : ""} line={1} />
            ) : (
              <VText title="采购天数" value={String(row.plan_lt_days.procurement_days) ? row.plan_lt_days.procurement_days + "天" : ""} line={1} />
            )}

            <div class="flex">
              <VText title="运输天数" value={String(row.plan_lt_days.transportation_days) ? row.plan_lt_days.transportation_days + "天" : ""} line={1} />
              <VText title="安全天数" value={String(row.plan_lt_days.safety_days) ? row.plan_lt_days.safety_days + "天" : ""} line={1} />
            </div>

            <div class="flex">
              <VText title="采购处理天数" value={String(row.plan_lt_days.procurement_processing_days) ? row.plan_lt_days.procurement_processing_days + "天" : ""} line={1} />

              <VText title="本地仓处理天数" value={String(row.plan_lt_days.local_warehouse_processing_days) ? row.plan_lt_days.local_warehouse_processing_days + "天" : ""} line={1} />
            </div>

            <div class="flex">
              <VText
                title="海外中转仓处理天"
                value={String(row.plan_lt_days.overseas_transit_warehouse_processing_days) ? row.plan_lt_days.overseas_transit_warehouse_processing_days + "天" : ""}
                line={1}
              />
              <VText title="平台上架天数" value={String(row.plan_lt_days.platform_listing_days) ? row.plan_lt_days.platform_listing_days + "天" : ""} line={1} />
            </div>
            <div>是否设置手动调整LT天数: {row?.plan_lt_days?.is_manually_edit == 1 ? "是" : "否"}</div>
          </div>
        ),
      },
    },

    {
      title: "库存可售天数",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <div>{row.plan_stocking_inventory_availability?.total_inventory_days} 天</div>
            <VText title="FBA可售" value={row.plan_stocking_inventory_availability?.fba_sellable_days ? row.plan_stocking_inventory_availability?.fba_sellable_days + "天" : ""} line={1} />
            <VText title="FBA在途" value={row.plan_stocking_inventory_availability.fba_in_transit_days ? row.plan_stocking_inventory_availability.fba_in_transit_days + "天" : ""} line={1} />
            <VText
              title="海外仓在途"
              value={row.plan_stocking_inventory_availability.overseas_warehouse_in_transit_days ? row.plan_stocking_inventory_availability.overseas_warehouse_in_transit_days + "天" : ""}
              line={1}
            />
            <VText
              title="海外仓可用"
              value={row.plan_stocking_inventory_availability.overseas_warehouse_available_days ? row.plan_stocking_inventory_availability.overseas_warehouse_available_days + "天" : ""}
              line={1}
            />
          </div>
        ),
      },
    },

    {
      title: "库存信息",
      width: 280,
      slots: {
        default: ({ row }) => (
          <div class="grid grid-cols-2 gap-x-2">
            <VText title="FBA可用" value={row.plan_asin_inventory.fba_available} line={1} />
            <VText title="本地仓可用" value={row.plan_asin_inventory.local_warehouse_available} line={1} />
            <VText title="本地仓待发" value={row.plan_asin_inventory.local_warehouse_pending_shipment} line={1} />
            <VText title="海外仓可用" value={row.plan_asin_inventory.overseas_warehouse_available} line={1} />
            <VText title="采购在途" value={row.plan_asin_inventory.procurement_in_transit} line={1} />
            <VText title="FBA在途" value={row.plan_asin_inventory.fba_in_transit} line={1} />
            <div class="flex items-center">
              <VText title="海外仓在途" value={row.plan_asin_inventory.overseas_warehouse_in_transit} line={1} />
              <svg-icon icon-class="edit_icon" class="cursor-pointer text-[#3487ff] text-[16px] mr-[4px]" onClick={() => openConfirmInput("overseas", row)} />
            </div>
            <div class="text-blue flex items-center cursor-pointer" onClick={() => InventoryDtlRef.value.open(row)}>
              库存信息 <svg-icon icon-class="baobiao" style="width:1.6em;height:1.6em"></svg-icon>
            </div>
          </div>
        ),
      },
    },

    {
      title: "销量信息",
      width: 180,
      slots: {
        header: ({}) => (
          <div>
            <span class="text-blue">7</span>/<span class="text-blue">14</span>/<span class="text-blue">30</span>/<span class="text-blue">90</span>天销量
          </div>
        ),
        default: ({ row }) => (
          <div class="grid grid-cols-2 gap-x-2">
            <VText title="7天" value={row.asin_sales?.sales_num_seven_days} line={1} onClick={() => console.log(row)} />
            <VText title="14天" value={row.asin_sales?.sales_num_fourteen_days} line={1} />
            <VText title="30天" value={row.asin_sales?.sales_num_thirty_days} line={1} />
            <VText title="90天" value={row.asin_sales?.sales_num_ninety_days} line={1} />
            <svg-icon icon-class="tubiao" class="text-[#3487ff] text-[1.5em]" onClick={() => AsinSalesTrendRef.value.open(row.id)} />
          </div>
        ),
      },
    },
    //  <svg-icon icon-class="more" />

    // <el-icon
    //   class={`mb-[-2px]  ${sorting.value.sorting_key == "system_average_daily_sales" && sorting.value.sorting_method == "asc" ? "sort-icon" : ""}`}
    //   onClick={() => onSort("system_average_daily_sales", "asc")}
    // >
    //   <CaretTop />
    // </el-icon>
    // <el-icon
    //   class={`${sorting.value.sorting_key == "system_average_daily_sales" && sorting.value.sorting_method == "desc" ? "sort-icon" : ""}`}
    //   onClick={() => onSort("system_average_daily_sales", "desc")}
    // >
    //   <CaretBottom />
    // </el-icon>
    {
      width: 180,
      slots: {
        header: ({}) => (
          <div>
            <div class="flex items-center mb-[6px]">
              系统预估日均销量
              <span class="flex" style="flex-direction:column">
                <div
                  style="font-size: 8px !important"
                  class={`dk-iconfont icon-CaretTop mb-[-4px]  ${sorting.value.sorting_key == "system_average_daily_sales" && sorting.value.sorting_method == "asc" ? "sort-icon" : ""}`}
                  onClick={() => onSort("system_average_daily_sales", "asc")}
                ></div>

                <div
                  style="font-size: 8px !important"
                  class={`dk-iconfont icon-CaretBottom mb-[-4px]  ${sorting.value.sorting_key == "system_average_daily_sales" && sorting.value.sorting_method == "desc" ? "sort-icon" : ""}`}
                  onClick={() => onSort("system_average_daily_sales", "desc")}
                ></div>
              </span>
            </div>
            <div class="flex items-center ">
              运营预测日均销量
              <span class="flex" style="flex-direction:column">
                <div
                  style="font-size: 8px !important"
                  class={`dk-iconfont icon-CaretTop mb-[-4px]  ${sorting.value.sorting_key == "operation_average_daily_sales" && sorting.value.sorting_method == "asc" ? "sort-icon" : ""}`}
                  onClick={() => onSort("operation_average_daily_sales", "asc")}
                ></div>

                <div
                  style="font-size: 8px !important"
                  class={`dk-iconfont icon-CaretBottom mb-[-4px]  ${sorting.value.sorting_key == "operation_average_daily_sales" && sorting.value.sorting_method == "desc" ? "sort-icon" : ""}`}
                  onClick={() => onSort("operation_average_daily_sales", "desc")}
                ></div>
              </span>
            </div>
          </div>
        ),
        // <el-icon
        //   class={`mb-[-2px]
        //  ${sorting.value.sorting_key == "operation_average_daily_sales" && sorting.value.sorting_method == "asc" ? "sort-icon" : ""}`}
        //   onClick={() => onSort("operation_average_daily_sales", "asc")}
        // >
        //   <CaretTop />
        // </el-icon>
        // <el-icon
        //   class={`${sorting.value.sorting_key == "operation_average_daily_sales" && sorting.value.sorting_method == "desc" ? "sort-icon" : ""}`}
        //   onClick={() => onSort("operation_average_daily_sales", "desc")}
        // >
        //   <CaretBottom />
        // </el-icon>

        default: ({ row }) => (
          <div>
            <VText title="系统" value={row.system_average_daily_sales} line={1} type="link" />
            <VText title="运营" value={row.operation_average_daily_sales} line={1} type="link" onClick={() => openTableInfo("forecastSales", row)} />
            <div>
              <span class="text-[var(--base-sub-text-color)]">计划:</span>
              <el-input
                v-model={row.plan_stocking_analysis.plan_average_daily_sales}
                placeholder="数量"
                style="width: 80px"
                onblur={() => dailySalesChange(row)}
                class="my-[4px]"
                oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
              />
            </div>

            <div class="mt-[6px]">
              {row.estimated_difference_text == "无" ? <span class="difference-text bg-[#c8c8c8]">销售预估无差异</span> : ""}
              {row.estimated_difference_text == "低" ? <span class="difference-text bg-[#f56c6c]">销售预估偏低</span> : ""}
              {row.estimated_difference_text == "高" ? <span class="difference-text bg-[#f56c6c]">销售预估偏高</span> : ""}
            </div>
          </div>
        ),
      },
    },

    {
      title: "销量对比",
      width: 100,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <span class="text-[#666]">按周:</span>
              {row.plan_stocking_analysis.weekly_sales_comparison != 0 ? (
                <svg-icon
                  icon-class={row.plan_stocking_analysis.weekly_sales_comparison == 2 ? "trend_ping" : row.plan_stocking_analysis.weekly_sales_comparison == 1 ? "trend_up" : "trend_down"}
                  class="text-[18px] ml-[2px]"
                />
              ) : (
                ""
              )}
            </div>

            <div class="flex items-center">
              <span class="text-[#666]">按月:</span>
              {row.plan_stocking_analysis.monthly_sales_comparison != 0 ? (
                <svg-icon
                  icon-class={row.plan_stocking_analysis.monthly_sales_comparison == 2 ? "trend_ping" : row.plan_stocking_analysis.monthly_sales_comparison == 1 ? "trend_up" : "trend_down"}
                  class="text-[18px] ml-[2px]"
                />
              ) : (
                ""
              )}
            </div>
          </div>
        ),
      },
    },
    {
      title: "销售毛利率",
      width: 100,
      slots: {
        default: ({ row }) => <div class="text-[20px]">--</div>,
      },
    },
    {
      title: "采购信息",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="采购价" value={row.plan_asin_purchases.purchase_price} line={1} />
            <VText title="起批量" value={row.plan_asin_purchases.min_order_quantity} line={1} />
            <VText title="采购天数" value={row.plan_asin_purchases.purchase_days} line={1} />
            <VText title="单箱数量" value={row.plan_asin_purchases.mpq_min_quantity} line={1} />
            <VText title="供应商" value={row.plan_asin_purchases.supplier_code || row.plan_asin_purchases.supplier_id} line={1} />
          </div>
        ),
      },
    },
    {
      title: "运输类型",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="类型" value={row?.plan_lt_days.transportation_type_text} line={1} />
            <VText title="运输天数" value={row?.plan_lt_days.transportation_days} line={1} />
            <VText title="最近FBA到货" value={row?.fba_received_quantity} line={1} />
            <VText title="到货时间" value={row?.fba_received_at} line={1} />
          </div>
        ),
      },
    },
    {
      title: "备料库存",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            {row.is_requires_stocking == 1 ? (
              <div class="text-red flex items-center">
                <svg-icon icon-class="wan" class="mr-[2px]"></svg-icon>需备料
              </div>
            ) : (
              ""
            )}

            <VText title="库存" value={row?.plan_stocking_analysis?.remaining_inventory} line={1} type="link" onClick={() => StockMaterialRef?.value.open(row)} />
          </div>
        ),
      },
    },
    {
      title: "人员信息",
      width: 200,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="计划" value={row.planner_user_text} line={1} />
            <VText title="采购" value={row.purchaser_user_text} line={1} />
            <VText title="运营" value={row.operator_user_text} line={1} />
            <VText title="部门" value={row.department_name} line={2} />
          </div>
        ),
      },
    },
    {
      title: "更新时间",
      width: 180,
      slots: {
        default: ({ row }) => <VText value={row.updated_at} />,
      },
    },

    {
      title: "操作",
      width: 80,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-button link type="primary" onClick={() => logRef?.value.open({ base_asin_id: row.id }, true)}>
                日志
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = {
          ...initForm(form),
          page: page.pageNum,
          page_size: page.pageSize,
        }
        console.log(archived_at.value)
        if (archived_at.value) {
          params.archived_at = archived_at.value
          return historyList(params)
        } else {
          return stockingAnalysisList(params)
        }
      },
    },
  },
})
const initForm = (form) => {
  let keys = ["sku", "custom_sku", "asin", "supplier_code"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v.trim())
    form[key] = form[key]?.map((v) => v.trim())
  })
  sorting.value = {
    sorting_key: form.sorting_key,
    sorting_method: form.sorting_method,
  }
  return form
}

import { getEnum, getAloneEnum } from "@/utils/enumUtils"
import { getSupplie, getAllSupplie } from "@/api"
import { getShopOptions } from "@/api/index.js"

// 获取下拉数据
const getOption = async () => {
  let keys = [...fieldList.value, ...highFieldList.value].filter((v) => v.originField)
  let enumParams = keys.filter((v) => v.enumOriginField).map((v) => v.originField)
  const enumData = await getEnum(enumParams, "enumOptions")
  let enumGetName = keys.filter((v) => !v.enumOriginField).map((v) => v.originField)
  enumGetName = [...enumGetName, "Plan.PlanStockingPlan.TypeEnum"]
  const data = await getEnum([...enumGetName], "enums")
  let optData = { ...enumData, ...data }
  for (const key in optData) {
    optData[key].length && (originOption.value[key] = optData[key])
  }
  originOption.value.amazonSite = (await getAloneEnum(["amazonSite"])).amazonSite

  // originOption.value.supplier = (await getSupplie())?.data
  // getAllSupplie
  // originOption.value.supplier = (await getSupplie())?.data

  // label: "supplier_name",
  // value: "supplier_code",
  let allSupplie = (await getAllSupplie()).data
  originOption.value.supplier = allSupplie
  originOption.value.supplierCode = allSupplie?.filter((v) => v.supplier_coding)
  const shopRes = await getShopOptions({ platform_ids: [2] })
  originOption.value.shopOpt = shopRes.data.map((n) => ({
    label: n.shop_name,
    value: n.shop_id,
  }))
}
// US,JP,CA,DE,IT,AU，UK,GB
</script>
<style lang="scss" scoped>
.basic_lead {
  width: 100%;
  background: #f6faff;
  padding: 16px 8px;
  text-align: center;
  border-radius: 4px;
}
:deep(.view-table) {
  .status-tag {
    // width: 30px;
    // height: 14px;
    // line-height: 14px;
    // text-align: center;
    // font-size: 10px;
  }
  .sort-icon {
    color: #3487ff;
  }
  .difference-text {
    padding: 2px 4px;
    border-radius: 4px;
    color: #fff;
  }
}
</style>
